package com.zzyl.nursing.service.member.Impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.memberDto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.member.MemberMapper;
import com.zzyl.nursing.service.member.IMemberService;
import com.zzyl.nursing.vo.LoginVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import com.zzyl.framework.web.service.TokenService;

@Service
@Slf4j
@RequiredArgsConstructor
public class MemberServiceImpl implements IMemberService {

    private final MemberMapper memberMapper;

    @Autowired
    private TokenService tokenService;

    @Value("${wx.appid}")
    private String appId;
    @Value("${wx.secret}")
    private String secret;
    private final static String CLIENT_CREDENTIAL = "client_credential";
    private final static String GRANT_TYPE = "authorization_code";
    private final static String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private final static String ACCESS_TOKEN = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private final static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";


    @Override
    public LoginVo loginUser(UserLoginRequestDto loginDao) {
        String openId = getOpenId(loginDao.getCode());
        log.info("openId:{}", openId);
        log.info("phoneCode:{}", loginDao.getPhoneCode());
        if (!StringUtils.hasText(openId)) {
            //抛出异常
            throw new RuntimeException("获取openId失败");
        }
        //判断这个openid在表中是否存在family_member（openid）
        FamilyMember member = memberMapper.selectOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));
        //如果不存在，我们就插入一条数据，如果存在则返回一条信息
        String token;
        LoginVo loginVo = new LoginVo();
        if (member == null) {
            member = new FamilyMember();
            member.setOpenId(openId);
            //获取手机号
            String phone = getPhone(loginDao.getPhoneCode());
            log.info("手机号：" + phone);
            member.setPhone(phone);
            member.setName("花开富贵");
            memberMapper.insert(member);
            //生成token
            token = createToken(member);
            log.info("token:" + token);
            loginVo = new LoginVo();
            loginVo.setToken(token);
            loginVo.setNickName(member.getName());
        } else if (member != null) {
            token = createToken(member);
            log.info("token:" + token);
            loginVo.setToken(token);
            loginVo.setNickName(member.getName());
        }
        return loginVo;
    }

    /**
     * 创建token
     * @param member
     * @return
     */
    private String createToken(FamilyMember member) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("id", member.getId());
        param.put("open_id", member.getOpenId());
        String token = tokenService.createToken(param);
        return token;
    }

    /**
     * 获取手机号
     * @param code
     * @return
     */
    private String getPhone(String code) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        String accessToken = getAccessToken();
        String response = HttpUtil.post(ACCESS_TOKEN + accessToken, JSONUtil.toJsonStr(param));
        JSON jsonObject = JSONUtil.parse(response);
        return jsonObject.getByPath("phone_info.phoneNumber") + "";
    }

    /**
     * 获取access_token
     * @return
     */
    private String getAccessToken() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("appid", appId);
        param.put("secret", secret);
        param.put("grant_type", CLIENT_CREDENTIAL);
        String response = HttpUtil.get(TOKEN_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(response);
        return jsonObject.getString("access_token");
    }

    /**
     * 获取openId
     * @param code
     * @return
     */
    private String getOpenId(String code) {
        //封装请求参数
        HashMap<String, Object> param = new HashMap<>();
        param.put("appid", appId);
        param.put("secret", secret);
        param.put("js_code", code);
        param.put("grant_type", GRANT_TYPE);
        String response = HttpUtil.get(OPENID_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
